package com.itheima.controller;

import com.itheima.commons.enums.ResultEnum;
import com.itheima.commons.enums.TipsEnum;
import com.itheima.commons.pojo.CommonEntity;
import com.itheima.commons.result.ResponseData;
import com.itheima.service.ElasticsearchDocumentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @program: itheima-technology-platform
 * @description: 文档操作控制器
 * @author: zhanghz001
 * @create: 2021-05-16 10:29
 **/
// @RestController
@RequestMapping("/v1/docs")
@Slf4j
public class ZhzElasticsearchDocController {
    @Autowired
    private ElasticsearchDocumentService elasticsearchDocumentService;
    
    /**
     * 全文检索
     *
     * @param commonEntity
     * @return
     */
    @GetMapping(value = "/mquery")
    public ResponseData mquery(CommonEntity commonEntity) {
        ResponseData responseData = new ResponseData();
        SearchResponse searchResponse = null;
        try {
            //通过高阶api调用批量查询操作功能
            searchResponse = elasticsearchDocumentService.matchQuery(commonEntity);
            
            //获取总数
            long total = searchResponse.getHits().getTotalHits().value;
            log.info("总数数据: {}  条", total);
            
            //当前数据多少条
            int dataLength = searchResponse.getHits().getHits().length;
            log.info("当前数据有: {} 条", dataLength);
            
            //通过类型自动装箱(多个参数取交集)
            responseData.setResultEnum(searchResponse.getHits().getHits(), ResultEnum.SUCCESS, (int) total);
            
            //日志记录
            log.info(TipsEnum.BATCH_GET_DOC_SUCCESS.getMessage());
        } catch (Exception e) {
            //日志记录
            log.error(TipsEnum.BATCH_GET_DOC_FAIL.getMessage(), e);
            //构造错误信息返回
            responseData.setResultEnum(ResultEnum.ERROR);
        }
        return responseData;
    }
    
    /**
     * 结构化搜索（查询手机在2000-3000元之间、京东物流发货，按照评价进行排序)
     *
     * @param commonEntity
     * @return
     */
    @GetMapping(value = "/tquery")
    public ResponseData tquery(CommonEntity commonEntity) {
        ResponseData responseData = new ResponseData();
        SearchResponse searchResponse = null;
        try {
            searchResponse = elasticsearchDocumentService.termQuery(commonEntity);
            long total = searchResponse.getHits().getTotalHits().value;
            log.info("总数数据: {}  条", total);
            
            int length = searchResponse.getHits().getHits().length;
            log.info("当前数据有: {} 条", length);
            
            //通过类型自动装箱(多个参数取交集)
            responseData.setResultEnum(searchResponse.getHits().getHits(), ResultEnum.SUCCESS, (int) total);
            //日志操作
            log.info(TipsEnum.BATCH_GET_DOC_SUCCESS.getMessage());
        } catch (Exception e) {
            log.error(TipsEnum.BATCH_GET_DOC_FAIL.getMessage(), e);
            //构造错误信息返回
            responseData.setResultEnum(ResultEnum.ERROR);
        } finally {
            
        }
        
        return responseData;
    }
    
    @PostMapping(value = "/batch")
    public ResponseData batch(@RequestBody CommonEntity commonEntity) {
        ResponseData responseData = new ResponseData();
        if (StringUtils.isEmpty(commonEntity.getIndexName()) ||
                CollectionUtils.isEmpty(commonEntity.getList())) {
            responseData.setResultEnum(ResultEnum.PARAM_ISNULL);
            return responseData;
        }
        //批量新增返回结果
        RestStatus restStatus = null;
        try {
            restStatus = elasticsearchDocumentService.bulkAddDoc(commonEntity);
            //装箱传递更多参数
            responseData.setResultEnum(restStatus, ResultEnum.SUCCESS, null);
            
            //日志记录
            log.info(TipsEnum.BATCH_CREATE_DOC_SUCCESS.getMessage());
        } catch (Exception e) {
            log.error(TipsEnum.BATCH_CREATE_DOC_FAIL.getMessage(), e);
            //构造错误信息返回
            responseData.setResultEnum(ResultEnum.ERROR);
        } finally {
            
        }
        
        return responseData;
    }
    
    /**
     * 自动补全查询
     * 自动补全 根据用户的输入联想到可能的词或者短语
     *
     * @param commonEntity
     * @return
     */
    @GetMapping("/csuggest")
    public ResponseData csuggest(@RequestBody CommonEntity commonEntity) {
        ResponseData responseData = new ResponseData();
        if (StringUtils.isEmpty(commonEntity.getIndexName()) ||
                StringUtils.isEmpty(commonEntity.getSuggestFileld()) ||
                StringUtils.isEmpty(commonEntity.getSuggestValue())) {
            responseData.setResultEnum(ResultEnum.PARAM_ISNULL);
            return responseData;
        }
        try {
            //查询到所有的建议列表
            List<String> suggest = elasticsearchDocumentService.cSuggest(commonEntity);
            //将所有的补全的单词加入到返回结果中
            responseData.setResultEnum(suggest, ResultEnum.SUCCESS, suggest.size());
            
            //记录日志
            log.info(TipsEnum.CSUGGEST_GET_DOC_SUCCESS.getMessage());
        } catch (Exception e) {
            //查询失败日志记录
            log.error(TipsEnum.CSUGGEST_GET_DOC_FAIL.getMessage(), e);
            //构建错误返回信息
            responseData.setResultEnum(ResultEnum.ERROR);
        }
        return responseData;
        
    }
    
    /**
     * 自动纠错接口
     *
     * @param commonEntity
     * @return
     */
    @GetMapping("/psuggest")
    public ResponseData psuggest(@RequestBody CommonEntity commonEntity) {
        //构造返回数据
        ResponseData rData = new ResponseData();
        if (StringUtils.isEmpty(commonEntity.getIndexName())
                || StringUtils.isEmpty(commonEntity.getSuggestFileld())
                || StringUtils.isEmpty(commonEntity.getSuggestValue())
        ) {
            rData.setResultEnum(ResultEnum.PARAM_ISNULL);
            return rData;
        }
        
        //批量查询返回结果
        try {
            String pSuggest = elasticsearchDocumentService.pSuggest(commonEntity);
            //通过类型推断自动装箱
            rData.setResultEnum(pSuggest, ResultEnum.SUCCESS, null);
            //记录日志
            log.info(TipsEnum.PSUGGEST_GET_DOC_SUCCESS.getMessage());
        } catch (Exception e) {
            log.error(TipsEnum.PSUGGEST_GET_DOC_FAIL.getMessage(), e);
            rData.setResultEnum(ResultEnum.ERROR);
        }
        return rData;
    }
    
    /**
     * 搜索推荐,搜索关键字过多的时候进行推荐
     *
     * @param commonEntity
     * @return
     */
    @GetMapping(value = "/tsuggest")
    public ResponseData tsuggest(@RequestBody CommonEntity commonEntity) {
        
        //构建返回数据
        ResponseData rData = new ResponseData();
        //
        if (StringUtils.isEmpty(commonEntity.getIndexName()) ||
                StringUtils.isEmpty(commonEntity.getSuggestFileld()) ||
                StringUtils.isEmpty(commonEntity.getSuggestValue())) {
            rData.setResultEnum(ResultEnum.PARAM_ISNULL);
            return rData;
        }
        //批量查询返回结果
        String result = null;
        try {
            //通过高阶API调用批量新增操作方法
            result = elasticsearchDocumentService.tSuggest(commonEntity);
            //通过类型推断自动装箱（多个参数取交集）
            rData.setResultEnum(result, ResultEnum.SUCCESS, null);
            //日志记录
            log.info(TipsEnum.TSUGGEST_GET_DOC_SUCCESS.getMessage());
        } catch (Exception e) {
            //日志记录
            log.error(TipsEnum.TSUGGEST_GET_DOC_FAIL.getMessage(), e);
            //构建错误返回信息
            rData.setResultEnum(ResultEnum.ERROR);
        }
        
        return rData;
    }
}
